﻿using ClientAppraise.ViewModels.Validator;
using ClientAppraise.Views.Pages.Corpus.CorpusAdornType.Controls;
using ClientDao.Corpus;
using ClientInfrastructure.Dto;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ShareCode.Dto;
using ShareCode.Dto.Corpus;
using ShareCode.Entity.Corpus;
using ShareCode.KeyValue.Corpus;
using ShareCode.Util.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ClientAppraise.ViewModels.Pages.Corpus.CorpusAdorn.Admin
{
    public partial class NewViewModel(CorpusAdornDal dal) : MyObservableValidator, IInitDataContextViewModel
    {
        CorpusAdornDal Dal = dal;

        public PageParameterDto? DataContext { get; private set; }

        public void InitDataContext(PageParameterDto? dataContext)
        {
            this.DataContext = dataContext;

            if (EnumList == default || EnumList.Count < 1)
            {
                EnumList = EnumHelper.GetAllItems<EnumCorpusAdornType>();
            }

            if (this.DataContext != default && this.DataContext.Model != null)
            {
                if (this.DataContext.Model is CorpusAdornWithTypeDto corpusAdornWithType)
                {
                    corpusAdornTypeId = corpusAdornWithType.CorpusAdornTypeId;
                    CorpusAdornTypeTitle = corpusAdornWithType.TypeTitle;

                    Title = corpusAdornWithType.Title;
                    Remarks = corpusAdornWithType.Remarks;
                    TheCode = corpusAdornWithType.TheCode;
                    Content = corpusAdornWithType.Content;
                    Sort = corpusAdornWithType.Sort;
                    TheType = corpusAdornWithType.TheType;
                }
            }
        }

        #region 属性
        [ObservableProperty]
        private List<EnumExtendModel> enumList = [];


        [ObservableProperty]
        private int sort;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? title;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? theCode;
        [ObservableProperty]
        private int theType;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? corpusAdornTypeTitle;
        private long corpusAdornTypeId;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? content;
        [ObservableProperty]
        private string? remarks;

        #endregion
        [ObservableProperty]
        private string? pageTitle = "新建语料装饰";

        private CorpusAdornEntity InitEntity(CorpusAdornEntity entity)
        {
            entity.Title = this.Title;
            entity.Remarks = this.Remarks;
            entity.TheCode = this.TheCode;
            entity.Content = this.Content;
            entity.CorpusAdornTypeId = this.corpusAdornTypeId;
            entity.Sort = this.Sort;
            entity.TheType = this.TheType;

            return entity;
        }


        [RelayCommand]
        private async Task OnSubmitAsync()
        {
            ValidateAllProperties();

            if (this.HasErrors)
            {
                App.MySnackbar.Danger("没有完成表单填写", "没有完成表单填写");
                return;
            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    CorpusAdornEntity entity = InitEntity(new CorpusAdornEntity());

                    if (DataContext != default && DataContext.Model is CorpusAdornEntity model)
                    {
                        if (DataContext.Do == PageParameterDtoDo.Update)
                        {
                            entity = InitEntity(model);
                        }
                    }

                    if (entity.Id == 0)
                    {
                        ResultDto<long> reslut = await Dal.InsertAsync(entity);
                        if (reslut.Success)
                        {
                            App.MySnackbar.Success("成功添加：" + entity.Title);
                            App.MyNavigation.GoBack();
                            return;
                        }

                        //显示错误信息
                        ValidateAllPropertiesWithServer(reslut?.DetailMSg ?? []);

                        if (!string.IsNullOrEmpty(reslut?.Message))
                        {
                            App.MySnackbar.Danger("添加失败:", reslut.Message);
                        }
                    }
                    else
                    {
                        ResultDto<bool> reslut = await Dal.UpdateAsync(entity);
                        if (reslut.Success)
                        {
                            App.MySnackbar.Success("成功修改：" + entity.Title);
                            App.MyNavigation.GoBack();
                            return;
                        }

                        //显示错误信息
                        ValidateAllPropertiesWithServer(reslut?.DetailMSg ?? []);

                        if (!string.IsNullOrEmpty(reslut?.Message))
                        {
                            App.MySnackbar.Danger("修改失败:", reslut.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    App.MySnackbar.Danger(ex.Message, ex.Message);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            });
        }

        public async Task ShowDrawerAsync()
        {
            if (!App.Current.Dispatcher.CheckAccess())
            {
                await Application.Current.Dispatcher.Invoke(async () => await ShowDrawerAsync());
                return;
            }

            var drawerReturn = await App.MyDrawer.ShowDrawer<UcCorpusAdornTypeSelector>(obj =>
            {
                if (obj is IInitDataContextViewModel model)
                {
                    model.InitDataContext(new PageParameterDto { Model = new List<long> { corpusAdornTypeId } });
                }
            });

            if (drawerReturn.Data is List<CorpusAdornTypeEntity> selected)
            {
                corpusAdornTypeId = selected.Select(x => x.Id).FirstOrDefault();
                CorpusAdornTypeTitle = selected.Select(y => y.Title).FirstOrDefault();

            }
            else
            {
                corpusAdornTypeId = 0;
                CorpusAdornTypeTitle = "";
            }

        }
    }
}
